package com.example.mpandroidchartdemo;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;


import java.util.ArrayList;
import java.util.List;

public class BarChartGroupActivity extends AppCompatActivity {

    private BarChart mBarChart;
    private List<BarEntry> list1 = new ArrayList<>();
    private List<BarEntry> list2 = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bar_chart_group_activity);
        mBarChart = findViewById(R.id.bar_chart_group);

        // 添加第一组数据
        list1.add(new BarEntry(1,5));
        list1.add(new BarEntry(2,7));
        list1.add(new BarEntry(3,12));
        list1.add(new BarEntry(4,3));
        list1.add(new BarEntry(5,9));

        // 添加第二组数据
        list2.add(new BarEntry(1,6));
        list2.add(new BarEntry(2,4));
        list2.add(new BarEntry(3,9));
        list2.add(new BarEntry(4,13));
        list2.add(new BarEntry(5,7));

        BarDataSet barDataSet1 = new BarDataSet(list1,"男");
        barDataSet1.setColor(Color.RED); // 设置第一组数据颜色
        BarDataSet barDataSet2 = new BarDataSet(list2,"女");
        barDataSet2.setColor(Color.BLUE); // 设置第二组数据颜色
        BarData barData = new BarData(barDataSet1); // 添加第一组数据
        barData.addDataSet(barDataSet2); // 添加第二组数据
        mBarChart.setData(barData);

        barData.setBarWidth(0.2F); // 设置柱子宽度
        // barData.groupBars()三个参数分别代表 -X轴起点 -组与组之间的间隔 -组内柱子的间隔
        barData.groupBars(1F,0.6F,0);

        mBarChart.getXAxis().setCenterAxisLabels(true); // 设置柱子（柱子组）居中对齐X轴上的点

        mBarChart.getXAxis().setAxisMaximum(6);
        mBarChart.getXAxis().setAxisMinimum(1);
        mBarChart.getXAxis().setLabelCount(5,false);

        mBarChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);   //X轴的位置设置为下  默认为上
        mBarChart.getAxisRight().setEnabled(false);     //右侧Y轴不显示   默认为显示
    }
}
